//201902104003邵潇漩
package bysj.dao;

import bysj.domain.*;
import java.sql.*;
import java.util.Collection;

public class ApplicationForSupervisorDao {
    private static ApplicationForSupervisorDao applicationForSupervisorDao = null;
    private ApplicationForSupervisorDao() {
    }

    public static ApplicationForSupervisorDao getInstance() {
        if (applicationForSupervisorDao == null){
            applicationForSupervisorDao = new ApplicationForSupervisorDao();
        }
        return applicationForSupervisorDao;
    }
    public int addApplicationForSupervisor(Connection conn, ApplicationForSupervisor applicationForSupervisor) throws SQLException {
        String addApplicationForSupervisor_sql = "INSERT INTO ApplicationForSupervisor " +
                "(selfIntroduction,student_id,year) value (?,?,?)";
        //在该连接上创建预编译语句对象
        PreparedStatement pstmt = conn.prepareStatement(addApplicationForSupervisor_sql, Statement.RETURN_GENERATED_KEYS);
        //为预编译参数赋值
        pstmt.setString(1, applicationForSupervisor.getSelfIntroduction());
        pstmt.setInt(2, applicationForSupervisor.getStudent().getId());
        pstmt.setInt(3, applicationForSupervisor.getYear());
        pstmt.execute();
        //执行批处理SQL语句
        int idOfAddedApplicationForSupervisor = 0;
        //获得生成的主键集合
        ResultSet resultSet = pstmt.getGeneratedKeys();
        if (resultSet.next()) {
            //读取第一个主键
            idOfAddedApplicationForSupervisor = resultSet.getInt(1);
        }
        return idOfAddedApplicationForSupervisor;
    }
    public boolean addApplicationForSupervisorEntry(Connection conn,
            Collection<ApplicationForSupervisorEntry> applicationForSupervisorEntries,
        int idOfAddedApplicationForSupervisor)throws SQLException{
        String addApplicationForSupervisorEntries_sql="INSERT INTO ApplicationForSupervisorEntry "+
                "(teacher_id,priority,applicationForSupervisor_id) value (?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(addApplicationForSupervisorEntries_sql);
        //为预编译参数赋值
        for(ApplicationForSupervisorEntry a:applicationForSupervisorEntries) {
            pstmt.setInt(1, a.getTeacher().getId());
            pstmt.setInt(2, a.getPriority());
            pstmt.setInt(3, idOfAddedApplicationForSupervisor);
            pstmt.addBatch();
        }
        int[] list=pstmt.executeBatch();
        return list.length>0;
    }
}
